package com.woniuxy.uumsweb.service;

import com.woniuxy.uumsweb.feign.LoginFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class LoginService {
    @Autowired
    private LoginFeign loginFeign;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse httpServletResponse;
    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    public String login(String username, String password) {
        //调用远程服务，如果返回值为空，则登录失败，返回登录页面，否则登录成功跳转首页
        String token = loginFeign.login(username, password);
        if(StringUtils.isEmpty(token)){
            //登录失败，怎么把登录失败提示给html
            request.setAttribute("msg","用户名或密码错误!");
            return "login";
        }
        //token保存到cookie中
        Cookie cookie = new Cookie("token",token);
        cookie.setDomain("localhost"); //域名
        cookie.setPath("/");
        httpServletResponse.addCookie(cookie);

        return "redirect:/";
    }
}
